package com.lvyq.myplayer.common.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
import androidx.palette.graphics.Palette
import com.lvyq.myplayer.R
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target

/**
 * 文件描述：PaletteColorUtils
 * 作者：lvyq
 * 创建时间：2025-07-28
 * 修改时间：2025-07-28
 */
class PaletteColorUtils {


    companion object {
        /**
         * 获取图片主色并设置背景色
         */
        suspend fun setBoxBackColor(context: Context, bgImg: String?, targetView: View) {
            if (!bgImg.isNullOrEmpty()) {
                Picasso.with(context).load(bgImg).into(object : Target {
                    override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) {
                        Palette.from(bitmap).generate { palette ->
                            val defaultColor = ContextCompat.getColor(context, R.color.white)
                            val dominantColor = palette?.dominantSwatch?.rgb ?: defaultColor
                            // 生成渐变色（主色 + 衍生色）
                            val gradientColors = createSmoothGradient(dominantColor, defaultColor)
                            // 创建渐变Drawable
                            val gradientDrawable = GradientDrawable(
                                GradientDrawable.Orientation.LEFT_RIGHT,
                                gradientColors
                            ).apply {
                                cornerRadius = 16f // 圆角
                            }

                            // 应用渐变背景（带平滑过渡）
                            targetView.background = gradientDrawable
                        }
                    }

                    override fun onBitmapFailed(errorDrawable: Drawable?) {
                    }

                    override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
                })
            }
        }


        // 生成渐变的颜色数组
        private fun createSmoothGradient(dominantColor: Int, defaultColor: Int): IntArray {
            return intArrayOf(
                // 生成三种渐变色阶
                //dominantColor,
                mixColors(dominantColor, defaultColor, 0.8f),
                mixColors(dominantColor, defaultColor, 0.8f)
                // defaultColor
            )
        }

        // 颜色混合工具函数
        private fun mixColors(color1: Int, color2: Int, ratio: Float): Int {
            return ColorUtils.blendARGB(color1, color2, ratio)
        }

    }
}